package com.ebn.mation.readagram;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.Toast;

import com.ebn.mation.readagram.gen.DaoSession;
import com.ebn.mation.readagram.gen.UserInfoBeanDao;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements UserInfoAdapter.IUserOnClick {

    private static final String TAG = "MainActivity";

    private SwipeRecyclerView mRvNews;
    private FloatingActionButton mFloatAddBtn;

    private UserInfoAdapter mUserInfoAdapter;

    private MyApplication mApplication;
    private DaoSession mDaoSession;
    private UserInfoBeanDao mUserInfoBeanDao;
    private List<UserInfoBean> mUserInfoBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initListener();
    }

    private void initListener() {
        mFloatAddBtn.setOnClickListener(v -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            AlertDialog alertDialog = dialog.create();
            View dialogView = getLayoutInflater().inflate(R.layout.dialog_user_info, null);

            ImageView imgExit = dialogView.findViewById(R.id.img_exit);
            imgExit.setOnClickListener(v1 -> {
                alertDialog.dismiss();
            });

            Button btnDone = dialogView.findViewById(R.id.btn_done);

            btnDone.setOnClickListener(v1 -> {
                EditText edtName = dialogView.findViewById(R.id.edt_name);
                String name = edtName.getText().toString().trim();

                EditText edtYear = dialogView.findViewById(R.id.edt_year);
                String year = edtYear.getText().toString().trim();

                EditText edtSubject = dialogView.findViewById(R.id.edt_subject);
                String subject = edtSubject.getText().toString().trim();

                EditText edtInstagram = dialogView.findViewById(R.id.edt_instagram);
                String instagram = edtInstagram.getText().toString().trim();

                EditText edtFirstComments = dialogView.findViewById(R.id.edt_first_comments);
                String firstComments = edtFirstComments.getText().toString().trim();

                RadioButton rabY = dialogView.findViewById(R.id.rab_y);
                boolean rabYCheck = rabY.isChecked();
                RadioButton rabN = dialogView.findViewById(R.id.rab_n);
                boolean rabNCheck = rabN.isChecked();

                RatingBar rbOverall = dialogView.findViewById(R.id.rb_overall);
                float rbNumStars = rbOverall.getRating();

                EditText edtTwoComments = dialogView.findViewById(R.id.edt_two_comments);
                String twoComments = edtTwoComments.getText().toString().trim();

                //完成添加
                UserInfoBean userTable = new UserInfoBean();
                userTable.setId((long) mUserInfoBeans.size());
                userTable.setName(name);
                userTable.setSemYear(year);
                userTable.setSubject(subject);
                userTable.setInstagram(instagram);
                userTable.setFirstComments(firstComments);
                if (rabYCheck) {
                    userTable.setReleasedPublic(1);
                }
                if (rabNCheck) {
                    userTable.setReleasedPublic(2);
                }
                userTable.setOverallExhibit(rbNumStars);
                userTable.setTwoComments(twoComments);
                mUserInfoBeanDao.insert(userTable);
                mUserInfoBeans.add(userTable);
                Toast.makeText(this,"添加成功！",Toast.LENGTH_SHORT).show();
                mUserInfoAdapter.setUserInfoList(mUserInfoBeans);
                mUserInfoAdapter.notifyDataSetChanged();
                alertDialog.dismiss();
            });
            alertDialog.setView(dialogView);
            alertDialog.show();
        });
    }

    private void initData() {
        mApplication = (MyApplication) this.getApplication();
        mDaoSession = mApplication.getDaoSession();
        mUserInfoBeanDao = mDaoSession.getUserInfoBeanDao();
        mUserInfoBeans = mUserInfoBeanDao.loadAll();

        mRvNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mUserInfoAdapter = new UserInfoAdapter(mUserInfoBeans);
        mRvNews.setSwipeMenuCreator(swipeMenuCreator);
        mRvNews.setOnItemMenuClickListener(mMenuItemClickListener);
        mRvNews.setAdapter(mUserInfoAdapter);
        mUserInfoAdapter.setIUserOnClick(this);
        mUserInfoAdapter.notifyDataSetChanged();
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = (swipeLeftMenu, swipeRightMenu, position) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        // 添加右侧的，如果不添加，则右侧不会出现菜单。
        {
            SwipeMenuItem deleteItem = new SwipeMenuItem(this).setBackground(R.color.red)
                    .setImage(R.drawable.icon_delete)
                    .setText("删除")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。
        }
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mMenuItemClickListener = (menuBridge, position) -> {
        menuBridge.closeMenu();

        int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
        int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

        UserInfoBean userTable = mUserInfoBeans.get(position);
        Log.d(TAG, "mMenuItemClickListener userTable: " + userTable.toString());

        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            Log.d(TAG, "mMenuItemClickListener menuPosition: " + menuPosition);
            if (menuPosition == 0) {
                //删除
                mUserInfoBeans.remove(position);
                mUserInfoBeanDao.delete(userTable);
                Toast.makeText(this,"删除成功！",Toast.LENGTH_SHORT).show();
                mUserInfoAdapter.notifyDataSetChanged();
            }

        }
    };

    private void initView() {
        mRvNews = findViewById(R.id.rv_news);
        mFloatAddBtn = findViewById(R.id.float_add_button);
    }

    @Override
    public void setUserClick(int position) {
        UserInfoBean userInfoBean = mUserInfoBeans.get(position);
        Log.d(TAG, "setUserClick userInfoBean: " + userInfoBean.toString());

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        AlertDialog alertDialog = dialog.create();
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_user_info, null);

        ImageView imgExit = dialogView.findViewById(R.id.img_exit);
        imgExit.setOnClickListener(v1 -> {
            alertDialog.dismiss();
        });

        EditText edtTwoComments = dialogView.findViewById(R.id.edt_two_comments);
        RatingBar rbOverall = dialogView.findViewById(R.id.rb_overall);
        RadioButton rabN = dialogView.findViewById(R.id.rab_n);
        RadioButton rabY = dialogView.findViewById(R.id.rab_y);
        EditText edtFirstComments = dialogView.findViewById(R.id.edt_first_comments);
        EditText edtInstagram = dialogView.findViewById(R.id.edt_instagram);
        EditText edtSubject = dialogView.findViewById(R.id.edt_subject);
        EditText edtYear = dialogView.findViewById(R.id.edt_year);
        EditText edtName = dialogView.findViewById(R.id.edt_name);

        Button btnDone = dialogView.findViewById(R.id.btn_done);
        btnDone.setOnClickListener(v1 -> {
            alertDialog.dismiss();
        });

        edtName.setText(userInfoBean.getName());
        edtYear.setText(userInfoBean.getSemYear());
        edtSubject.setText(userInfoBean.getSubject());
        edtInstagram.setText(userInfoBean.getInstagram());
        edtFirstComments.setText(userInfoBean.getFirstComments());
        edtTwoComments.setText(userInfoBean.getTwoComments());

        rbOverall.setRating(userInfoBean.getOverallExhibit());
        int releasedPublic = userInfoBean.getReleasedPublic();
        if (releasedPublic == 1) {
            rabY.setChecked(true);
        }
        if (releasedPublic == 2) {
            rabN.setChecked(true);
        }

        alertDialog.setView(dialogView);
        alertDialog.show();
    }
}